var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var global = require("global")

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var userInfoRouter = require('./routes/userPage/index')

var app = express();


// 连接mogodb
var mongoose = require('mongoose')

// var uri = 'mongodb://localhost/mongoose-shared-connection'
var uri = 'mongodb://localhost/mongoose-node-express'
global.db = mongoose.createConnection(uri, { useNewUrlParser: true });

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log('mongoose connect success')
    var port = process.env.PORT || 3001
    //监听http请求
    app.listen(port)
    console.log('port open at http://localhost:' + port)
});

// var opera = require('./mogoose/modelOpera')
//
// app.get('/getList', opera.home)
// app.get('/getModelName', opera.modelName)
// app.get('/addInfo', opera.insert)

app.set('views', path.join(__dirname, 'views')); //设置模板目录: views
app.set('view engine', 'ejs'); //设置模板引擎: ejs

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/project', userInfoRouter)

/*****************************路由配置 start****************************************/
// var loginRouter = require('./routes/common/login')
// app.use('/login', loginRouter)

/*****************************路由配置 end****************************************/

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
